package org.example.helloworld.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.helloworld.entity.Result;
import org.example.helloworld.entity.User;
import org.example.helloworld.service.INoticeService;
import org.example.helloworld.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 业主 前端控制器
 * </p>
 *
 * @author author
 * @since 2024-07-06
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private INoticeService noticeService;

    //    登录功能

    @RequestMapping("/login")
    public Result login(@RequestBody User user) {

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername()).
                eq("pwd", user.getPwd());

        User getUser = userService.getOne(queryWrapper);

        if (getUser != null) {
            return Result.success(getUser);
        }
        return Result.error("用户名或密码错误");
    }

    @RequestMapping("/register")
    public String register(@RequestBody User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());

        if (userService.getOne(queryWrapper) != null) {
            // 用户名已存在
            return "fail";
        } else {
            boolean result = userService.save(user);
        }
        return "success";
    }

    @GetMapping("/getUser")
    public Result getUser(@RequestParam("userId") Long userId) {
        if (userId == null || userId.describeConstable().isEmpty()) {
            return Result.error("User ID cannot be null or empty");
        }

        try {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);

            User user = userService.getOne(queryWrapper);
            if (user == null) {
                return Result.error("User not found");
            }

            return Result.success(user);
        } catch (Exception e) {
            return Result.error("Failed to fetch user data: " + e.getMessage());
        }
    }

    @PostMapping("/add")
    public Result addUser(@RequestBody User user) {
        boolean isSuccess = userService.save(user);
        return isSuccess ? Result.success() : Result.error("添加失败");
    }

    @PutMapping("/{id}")
    public Result updateUser(@PathVariable Long id, @RequestBody User user) {
        user.setUserId(id);
        boolean isSuccess = userService.updateById(user);
        return isSuccess ? Result.success() : Result.error("更新失败");
    }

    @DeleteMapping("/{id}")
    public Result deleteUser(@PathVariable Long id) {
        boolean isSuccess = userService.removeById(id);
        return isSuccess ? Result.success() : Result.error("删除失败");
    }

    @PostMapping("/batchDelete")
    public Result batchDelete(@RequestBody Map<String, List<Long>> request) {
        List<Long> ids = request.get("ids");
        if (ids == null || ids.isEmpty()) {
            return Result.error("未提供要删除的用户ID");
        }
        boolean isSuccess = userService.removeByIds(ids);
        return isSuccess ? Result.success() : Result.error("删除失败");
    }

    @GetMapping("/list")
    public Result list(
            @RequestParam int page,
            @RequestParam int size,
            @RequestParam(required = false) String search) {
        Page<User> userPage = new Page<>(page, size);
        IPage<User> resultPage = userService.getUserList(userPage, search);
        return Result.success(resultPage);
    }


    @PostMapping("/update")
    public Result updateUser(@RequestBody User user) {
        try {
            boolean updated = userService.updateById(user);
            if (updated) {
                return Result.success("User updated successfully");
            } else {
                return Result.error("Failed to update user");
            }
        } catch (Exception e) {
            return Result.error("Failed to update user data: " + e.getMessage());
        }
    }


//    @RequestMapping("/update")
//    public Result update(@RequestBody User user) {
////        修改
//        if (user.getUsername() != null && user.getUsername().length() > 0 &&
//                user.getRealname() != null && user.getRealname().length() > 0 &&
//                user.getPhone() != null && user.getPhone().length() > 0 &&
//                user.getPlace() != null && user.getPlace().length() > 0 &&
//                user.getBirth() != null && user.getBirth().length() > 0 &&
//                user.getPwd() != null && user.getPwd().length() > 0
//        ) {
//            boolean result = userService.updateById(user);
//            if (result) {
//                return Result.success();
//            }
//        }
//        return Result.error("格式不正确，请重新修改");
//    }



    @PostMapping("/updatePassword")
    public Result updatePassword(@RequestBody Map<String, String> request) {
        String userId = request.get("userId");
        String newPassword = request.get("newPassword");

        if (userId == null || userId.isEmpty() || newPassword == null || newPassword.isEmpty()) {
            return Result.error("User ID and new password cannot be null or empty");
        }

        try {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);

            User user = userService.getOne(queryWrapper);
            if (user == null) {
                return Result.error("User not found");
            }

            user.setPwd(newPassword);
            boolean updated = userService.updateById(user);
            if (updated) {
                return Result.success("Password updated successfully");
            } else {
                return Result.error("Failed to update password");
            }
        } catch (Exception e) {
            return Result.error("Failed to update password: " + e.getMessage());
        }
    }
}






